/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mycompany.searchingproteins;

import javax.swing.table.DefaultTableModel;
import uk.ac.ebi.pride.tools.jmzreader.model.Spectrum;
import uk.ac.ebi.pride.mzgraph.chart.graph.SpectrumPanel;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;//TableRowSorter;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/**
 *
 * @author Alicia
 */
public class mzMLFrame extends javax.swing.JFrame {

    mgf mgfObject;
    SpectrumPanel chartPanel;
     private RowSorter<TableModel> fSorter;
   
    /**
     * Creates new form mzMLFrame
     */
    public mzMLFrame() {
        initComponents();
        mgfObject=new mgf ();
                   
    }
    public void  mzMLFrame(String fileName){
            mgfObject.setFileName(fileName);
    
    }
    
    public mgf getMGF(){
        return mgfObject;
    
    }

    public SpectrumPanel getChartPanel(){
        return chartPanel;
    
    }
    
    public JTable getSpectrumTable (){
        return spectrumTable;
    
    }
    
    
    
    public void chargeDataTableSpectrum (mgf mgfObject) {
    
     String[] columnNames = {"Spectrum Id",
                        "Spectrum Name",
                        "MS Level",
                        "Identified",
                        "Precursor Charge",
                        "Precursor m/z",
                        "Precursor Intensity",
                        "Sum of Intensity",
                        "#Peaks"};
          
      Object[][] rows = new Object [mgfObject.getNumberSpectra()][9];
    
      List<Spectrum> lSpectrum = mgfObject.getListPeak();
      int j=0;
      for (Spectrum s : lSpectrum) {
                 // Getting the nameSpectrum 
                 String aux = mgfObject.getListPeak().get(Integer.parseInt(s.getId())-1).toString(); 
                 String [] aux3 = new String [1];
                 aux3= aux.split("\n");
                 String [] aux4 = new String [2];
                 
                 boolean found=false;
                 //System.out.print("aux3.length--> "+aux3.length+"\n");
                 //System.out.print("aux3[0]--> "+aux3[0]+"\n");
                 for(int i=0;i<aux3.length && !found;i++){
                     //System.out.print("fuera aux[3]--> "+aux3+"\n");
                     if(aux3[i].startsWith("title=".toUpperCase()) || aux3[i].startsWith("TITLE=")){
                         found=true;
                         aux4=aux3[i].split("=");
                          //System.out.print("aux[3]--> "+aux3+"\n");
                     } //end if
                 } //end for
                 
                // System.out.print("aux[4]--> "+aux4[1]+"\n");
                
                 rows[j][0]=Integer.parseInt(s.getId());
                 rows[j][1]=aux4[1];
                 rows[j][2]=s.getMsLevel(); 
                 rows[j][3]="????";
                 rows[j][4]=s.getPrecursorCharge();
                 rows[j][5]=s.getPrecursorMZ();
                 rows[j][6]=s.getPrecursorIntensity();
                 rows[j][7]="Calcular suma";
                 rows[j][8]="calcular numero picos";
                 
                  j++;
                 
        } //end for s
        
      //Creating a sorted model
      TableModel model= new DefaultTableModel(rows,columnNames){
             
             @Override
             public Class<?> getColumnClass(int columnIndex) {
                    Object val = getValueAt(0, columnIndex);
                    return val == null ? Object.class : val.getClass();
            }
             
       };
        
       //Changing for no editable columns
       for (int c = 0; c < spectrumTable.getColumnCount(); c++)
        {
               Class<?> col_class = spectrumTable.getColumnClass(c);
               spectrumTable.setDefaultEditor(col_class, null); // remove editor
        } //end for
        
        

        //For selecting a row with mouse
        spectrumTable.setColumnSelectionAllowed(false);
        spectrumTable.setRowSelectionAllowed(true);
        spectrumTable.changeSelection(0, 0, false, false);
        spectrumTable.setAutoCreateRowSorter(true);
        
        
        /**************************************************/
        //Setting the table model
        spectrumTable.setModel(model);

        //Setting the columns sorter
        fSorter = new TableRowSorter<TableModel>(model);
        spectrumTable.setRowSorter(fSorter);
       
        /**************************************************/
        
        //setting the first spectrum by default
        double [] mzArr=null;
        double [] intentArr=null;
        Object [] mzIntentArr=null;
        //Getting arrays for printing spectra
        mzIntentArr=this.getMGF().ConvertSpectrumtoVector(0);
        mzArr = (double [])mzIntentArr[0];
        intentArr = (double [])mzIntentArr[1];
        this.chargeGraphic(mzArr, intentArr);
        
        
    }       
  
    
    public void chargeGraphic(double [] mzArr, double intentArr[]) {
        
        chartPanel = new SpectrumPanel(mzArr, intentArr);
        
        chartPanel.paintGraph();
        chartPanel.setGridLineVisibility(false);      
       
        jTabbedPane1.removeAll();
        jTabbedPane1.addTab("Spectrum", chartPanel);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jTabbedPane1.setVisible(true);
    
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        spectrumTable = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jSeparator2 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        spectrumTable.setAutoCreateRowSorter(true);
        spectrumTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Spectrum Id", "Spectrum Name", "MS Level", "Identified", "Precursor Charge", "Precursor m/z", "Precursor Intensity", "Sum of Intensity", "#Peaks"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        spectrumTable.setColumnSelectionAllowed(true);
        spectrumTable.setRowSorter(spectrumTable.getRowSorter());
        spectrumTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                spectrumTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(spectrumTable);
        spectrumTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        if (spectrumTable.getColumnModel().getColumnCount() > 0) {
            spectrumTable.getColumnModel().getColumn(0).setHeaderValue("Spectrum Id");
            spectrumTable.getColumnModel().getColumn(1).setHeaderValue("Spectrum Name");
            spectrumTable.getColumnModel().getColumn(2).setHeaderValue("MS Level");
            spectrumTable.getColumnModel().getColumn(3).setHeaderValue("Identified");
            spectrumTable.getColumnModel().getColumn(4).setHeaderValue("Precursor Charge");
            spectrumTable.getColumnModel().getColumn(5).setHeaderValue("Precursor m/z");
            spectrumTable.getColumnModel().getColumn(6).setHeaderValue("Precursor Intensity");
            spectrumTable.getColumnModel().getColumn(7).setHeaderValue("Sum of Intensity");
            spectrumTable.getColumnModel().getColumn(8).setHeaderValue("#Peaks");
        }

        jButton1.setText("Exit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("< Back");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1020, Short.MAX_VALUE)
            .addComponent(jSeparator1)
            .addComponent(jTabbedPane1)
            .addComponent(jSeparator2)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void spectrumTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_spectrumTableMouseClicked
        // TODO add your handling code here:
        
        //listening to a row
        int row=spectrumTable.getSelectedRow();
        //get Spectrum id
        Object cellValue=spectrumTable.getValueAt(row, 0);
       // System.out.print("obj--> "+cellValue+"\n");
        //Getting arrays for printing spectra 
        Object [] mzIntentArr= mgfObject.ConvertSpectrumtoVector(Integer.parseInt(cellValue.toString())-1);
        double [] mzArr = (double [])mzIntentArr[0];
        double [] intentArr = (double [])mzIntentArr[1];
        
        chargeGraphic(mzArr, intentArr);
        //System.out.print("cellValue --> "+cellValue+"\n");
        
    }//GEN-LAST:event_spectrumTableMouseClicked

    
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        welcomeUI panel1 = new welcomeUI();       
        panel1.setVisible(true);
        
        setVisible(false);
        dispose(); // destroy object
    }//GEN-LAST:event_jButton2ActionPerformed

 

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable spectrumTable;
    // End of variables declaration//GEN-END:variables
}
